//*******************自定义**************************
var legalCurrencyUnitNumbers = [[], [2, 2, 2], [2, 3, 2]];
var digitCurrencySymbols = ['฿', 'Ł', 'E'];
var global = {
	siteFlag : site_flag,
	symbol: +document.getElementById("symbol").value,
	merge: Number(getCookieValue("deptMerge_stock")), // 0, 1, 2
	depthInit: false,
	currencyWord: site_flag == 1? "cny" : "usd",
	currencySymbol: site_flag == 1? "￥" : "$",
	btc: 0,
	ltc: 1,
	btcSymbol: digitCurrencySymbols[0],
	ltcSymbol: digitCurrencySymbols[1],
	legalCurrencyUnitNumber: legalCurrencyUnitNumbers[site_flag],
};

var subOption = function () {
    var result;
	if(site_flag==1){
        result= {
            'ok_sub_spotcny_userinfo': dealAccountInfo,
            'login': getCookieValue('coin_session_user_id')
        };
	}else{
        result= {
            'ok_sub_spotusd_userinfo': dealAccountInfo,
            'login': getCookieValue('coin_session_user_id')
        };
	}
	if(!result){
		return;
	}
	var subSpotBtcTickerName = WsUtils.getSubSpotTicker(global.btc);
	var subSpotLtcTickerName = WsUtils.getSubSpotTicker(global.ltc);
	var subSpotDepthName = WsUtils.getSubSpot5Depth(global.symbol, getCookieValue("deptMerge_stock"), global.siteFlag);
	var personalOrderInfoName = WsUtils.getSpotPersonalOrderInfo(global.symbol);
	
	eval('result["' + subSpotBtcTickerName + '"]=dealSpotBtcTicker;');
	eval('result["' + subSpotLtcTickerName + '"]=dealSpotLtcTicker;');
	eval('result["' + subSpotDepthName + '"]=dealSpotDepth;');
	eval('result["' + personalOrderInfoName + '"]=dealSpotOrderInfo;');
	return result;
}();

//**************************************************

var webSocket = new ws(subOption, dealErrorEvent, site_flag);
var depthManager = new depthManager();
var tickerManager = new tickerManager();

function dealErrorEvent() {
	// 询轮方法
	loopRequest();
}

function changeMergeType() {
	depthManager.changeMergeType();
}

// 连接
webSocket.tryConnect();

function loopRequest() {
	if (islogin) {
		refreshTradeBaner();//banner
		handleEntrust();//交易中心深度
		refrushRecord_push_pack();//现货交易最近10笔刷新
		handleTicker();
	}
}
//*******************自定义**************************
function dealSpotOrderInfo(data) {
	var orderSymbol = 1;
	if (data.symbol.indexOf("btc") != -1) {
		orderSymbol = 0;
	}
	dealSpotOrder(data, orderSymbol);
}

function dealSpotDepth(data) {
	depthManager.handleDepthData(data);
}

function dealSpotOrder(data, currentSymbol) {
	if (currentSymbol != global.symbol) {
		return;
	}
	var cur = document.getElementById("his_n").className;
	if (cur == "cur")
		return null;
	var tb = document.getElementById("tenorders");    //获取table对像
	var rows = tb.rows;
	var hasRow = false;
	var pushdata = {
		data: data
	};
	if (pushdata.data.tradeType.indexOf("buy") != -1) {
		pushdata.data.tradeType = 1;
	} else {
		pushdata.data.tradeType = 2;
	}
	var entrustSign = SYMBOLS_UTIL.symbolStr[Number(global.symbol)];
	for (var q = 1; q < rows.length; q++) {    //--循环所有的行
		var cells = rows[q].cells;
		var id = cells[0].innerHTML;
		if (id == pushdata.data.id) {//存在相同id
			if (pushdata.data.status == 2 || pushdata.data.status == -1) {//完全成交或撤单
				tb.deleteRow(q);
				if (rows.length == 1) {
					var trn = tb.insertRow(1);
					trn.innerHTML = "<td colspan='9' align='center'>" + get$('trade_entrust_ten_yhnoo') + "</td>";
				}
			} else if (pushdata.data.status == 1) {//部分成交
				cells[5].innerHTML = entrustSign + pushdata.data.completedTradeAmount;
//                                        cells[6].innerHTML = cnyOrUsdSymbol+pushdata.data.turnover;
				cells[6].innerHTML = cnyOrUsdSymbol + pushdata.data.averagePrice;
				if (pushdata.data.tradeUnitPrice == '1000000' && pushdata.data.tradeType == 1) {
					cells[7].innerHTML = cnyOrUsdSymbol + pushdata.data.unTrade;
				} else {
					cells[7].innerHTML = entrustSign + pushdata.data.unTrade;
				}
				cells[8].innerHTML = "(" + get$("trade_entrust_ten_partfulfilled") + ")" + "<a href='javascript:void(0);' onclick='javascript:cancelEntrust(" + pushdata.data.id + ");'>" + get$("trade_entrust_ten_cancel") + "</a>";
			}
			hasRow = true;
			break;
		}
	}
	if (!hasRow) {//新增一行
		if (pushdata.data.status == 2 || pushdata.data.status == -1 || pushdata.data.status == 1) {//完全成交或撤单或部分成交)
			return;
		}
		if (rows.length == 2 && rows[1].cells.length == 1) {
			tb.deleteRow(1);
		}
		var tr = tb.insertRow(1);
		var td = document.createElement("td");
		td.style.cssText = 'display:none';
		td.appendChild(document.createTextNode(pushdata.data.orderId));
		tr.appendChild(td);
		var td = document.createElement("td");
		td.appendChild(document.createTextNode(new Date(pushdata.data.createdDate).Format('yyyy-MM-dd hh:mm:ss')));
		td.setAttribute("class", "gray");
		tr.appendChild(td);
		var td = document.createElement("td");
		if (pushdata.data.tradeType == 1) {
			td.setAttribute("class", "lightgreen5");
		} else {
			td.setAttribute("class", "red");
		}
		td.appendChild(document.createTextNode(pushdata.data.tradeType == '1' ? get$("trade_entrust_ten_bid") : get$("trade_entrust_ten_ask")));
		tr.appendChild(td);
		var td = document.createElement("td");
		if ((pushdata.data.tradeType == 1 && (+pushdata.data.tradeUnitPrice) != 1000000) || pushdata.data.tradeType == 2) {
			td.appendChild(document.createTextNode(entrustSign + pushdata.data.tradeAmount));
		} else {
			td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.tradeAmount));
		}
		tr.appendChild(td);
		var td = document.createElement("td");
		if ((pushdata.data.tradeType == 1 && (+pushdata.data.tradeUnitPrice) != 1000000) || (pushdata.data.tradeType == 2 && +pushdata.data.tradeUnitPrice!= 0)) {
			td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.tradeUnitPrice));
		} else {
			td.appendChild(document.createTextNode(get$("trade_entrust_ten_instant")));
		}
		tr.appendChild(td);
		var td = document.createElement("td");
		td.appendChild(document.createTextNode(entrustSign + pushdata.data.completedTradeAmount));
		tr.appendChild(td);
		var td = document.createElement("td");
		td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.averagePrice));
		tr.appendChild(td);
		var td = document.createElement("td");
		if (pushdata.data.status == 0 || pushdata.data.status == 1 || pushdata.data.status == 3) {
			if (pushdata.data.tradeUnitPrice == '1000000' && pushdata.data.tradeType == 1) {
				td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.unTrade));
			} else {
				td.appendChild(document.createTextNode(entrustSign + pushdata.data.unTrade));
			}
		} else {
			td.appendChild(document.createTextNode(pushdata.data.unTrade));
		}
		tr.appendChild(td);
		var td = document.createElement("td");
		td.setAttribute("id", "entrustStatus" + pushdata.data.orderId);
		var statusClass = "";
		var status = "";
		if (pushdata.data.status == 0 || pushdata.data.status == 1 || pushdata.data.status == 3) {
			if (pushdata.data.status == 1) {
				status = "(" + get$("trade_entrust_ten_partfulfilled") + ")";
			} else if (pushdata.data.status == 0) {
				status = "(" + get$("trade_entrust_ten_unfilled") + ")";
			} else if (pushdata.data.status == 3) {
				status = "(" + get$("trade_entrust_ten_unfilled") + ")";
			}
			status = status + "<a href='javascript:void(0);' onclick='javascript:cancelEntrust(" + pushdata.data.orderId + ");'>" + get$("trade_entrust_ten_cancel") + "</a>";
			statusClass = "blue";
		} else if (pushdata.data.status == 2) {
			status = get$("trade_entrust_ten_fulfilled");
			statusClass = "lightgreen5";
		} else {
			status = get$("trade_entrust_ten_cancelled");
			statusClass = "gray";
		}
		td.setAttribute("class", statusClass);
		td.innerHTML = status;
		tr.appendChild(td);
		if (rows.length >= 12) {
			tb.deleteRow(11);
		}
		
	}
	if (pushdata.data.status == 2) {
		NotifyMsg.showMsg(this.getShowTitle(pushdata.data), getshowMsg(pushdata.data), function () {
			jQuery("#his_n a").click();
		});
	}
	this.getShowTitle = function(order){
		var symbol=jQuery("#symbol").val();
		var msg=SYMBOLS_UTIL.symbolStr2[symbol];
		msg += order.tradeType == 1 ? get$("immediatelybuy") : get$("immediatelysell");
		if(order.tradeUnitPrice == 1000000||order.tradeUnitPrice ==0) {
			msg +=get$("trade_entrust_ten_instant");
		}else{
			msg+=get$("futureplanentrust2");
		}
		msg+=get$("alreadDeall");
		return msg;
	}
}

function dealAccountInfo(data) {
	trade_injectUserParam(userInfoFormatToOldSocketFormat(data));
}

function userInfoFormatToOldSocketFormat(data) {
	var res = {};
	if (global.siteFlag == 1) {
		res.cnyBalance = data.info.free.cny;
		res.freezeCnyBalance = data.info.freezed.cny;
		res.lendCnyBalance = data.info.lend.cny;
		res.lendFreezeCnyBalance = data.info.lendFreeze.cny;
		res.lendedCnyBalance = data.info.lended.cny;
		res.borrowCnyBalance = data.info.borrow.cny;
		res.binterestCnyBalance = data.info.binterest.cny;
	} else {
		res.cnyBalance = data.info.free.usd;
		res.freezeCnyBalance = data.info.freezed.usd;
		res.lendCnyBalance = data.info.lend.usd;
		res.lendFreezeCnyBalance = data.info.lendFreeze.usd;
		res.lendedCnyBalance = data.info.lended.usd;
		res.borrowCnyBalance = data.info.borrow.usd;
		res.binterestCnyBalance = data.info.binterest.usd;
	}
	res.btcBalance = Number(data.info.free.btc);
	res.ltcBalance = Number(data.info.free.ltc);
	res.freezeBtcBalance = data.info.freezed.btc;
	res.freezeLtcBalance = data.info.freezed.ltc;
	res.lendBtcBalance = data.info.lend.btc;
	res.lendLtcBalance = data.info.lend.ltc;
	res.lendedBtcBalance = data.info.lended.btc;
	res.lendedLtcBalance = data.info.lended.ltc;
	res.lendFreezeBtcBalance = data.info.lendFreeze.btc;
	res.lendFreezeLtcBalance = data.info.lendFreeze.ltc;
	res.fundBtcBalance = data.info.fund.btc;
	res.fundLtcBalance = data.info.fund.ltc;
	res.borrowBtcBalance = data.info.borrow.btc;
	res.borrowLtcBalance = data.info.borrow.ltc;
	res.binterestBtcBalance = data.info.binterest.btc;
	res.binterestLtcBalance = data.info.binterest.ltc;
	
	res.borrowFreeze = data.borrowFreeze;
	return res;
}

function formatTickerData(data, bit) {
    data.vol = CommaFormattedByOriginal(data.vol + "");
    data.last = Number(data.last).toFixed(bit);
    return data;
}

function dealSpotBtcTicker(data) {
    data = formatTickerData(data, global.legalCurrencyUnitNumber[global.btc]);
    tickerManager.dealSpotBtcTicker(data);
}
function dealSpotLtcTicker(data) {
    data = formatTickerData(data, global.legalCurrencyUnitNumber[global.ltc]);
    tickerManager.dealSpotLtcTicker(data);
}

function tickerManager() {
	this.refreshTitlePrice = function(data) {
		// 修改title
		var oldTitle = document.title;
		var arrs = oldTitle.split("-");
		//前辍用来判断title是显示BTC还是LTC
		if(oldTitle!=null&&oldTitle.length>0){
			if(arrs.length > 0){
				oldTitle = arrs[arrs.length-1];
			}
			var newTitle =  global.currencySymbol+data.last+"-"+oldTitle;
			
			//newCoinLabel
			if(global.symbol==0){
				newTitle = ":"+global.currencySymbol+data.last+"-"+oldTitle;
			}else if(global.symbol== 1) {
				newTitle = ":"+global.currencySymbol+data.last+"-"+oldTitle;
			}
			return newTitle;
		}
		return "";
	};
	this.checkBanner = function () {
		if (document.getElementById('bannerAccountBtcLast') == null || !islogin) {
			return false;
		}
		return true;
	};
	this.dealSpotLtcTicker = function (data) {
		// 更新title上的价格
		if(global.symbol == global.ltc && document.title!=null && !isSpider() && data.last != 0) {
			var newTitle = this.refreshTitlePrice(data);
			if (newTitle != "") {
				document.title = global.ltcSymbol + newTitle;
			}
		}
		if (!this.checkBanner()) {
			return;
		}
		
		if (data != null && data != '' && data != 'undefined') {
			if (document.getElementById("bannerAccountLtcLast") != null && data.last != null && data.last != '' && data.last != 'undefined') {
				document.getElementById("bannerAccountLtcLast").value = data.last;
				push.btclast = Number(document.getElementById('bannerAccountLtcLast').value);
			}
			if (document.getElementById("bannerLtcBuy") != null && data.buy != null && data.buy != '' && data.buy != 'undefined') {
				document.getElementById("bannerLtcBuy").value = data.buy;
			}
			if (document.getElementById("bannerLtcSell") != null && data.sell != null && data.sell != '' && data.sell != 'undefined') {
				document.getElementById("bannerLtcSell").value = data.sell;
			}
			AccountingUserAccountInfo();
			if (document.getElementById("canpush") != null) {
				_ChangeBalance();
			}
		}
		if (document.getElementById("bannerLtcLast") != null) {
			push.ltclast = data.last;
			push.ltcsell = data.sell;
			push.ltcbuy = data.buy;
			document.getElementById("bannerLtcLast").innerHTML = (push.ltclast + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
		}
		if (document.getElementById("bannerLtcVol") != null) {
			var tempLtc = data.vol + '';
			var end = tempLtc.indexOf('.');
			if (end == -1) {
				end = tempLtc.length;
			}
			document.getElementById("bannerLtcVol").innerHTML = tempLtc.substr(0, end);
		}
		if (document.getElementById("indexLtcVol") != null) {
			document.getElementById("indexLtcVol").innerHTML = data.vol;
		}
		if (global.symbol == 1 && document.getElementById("tradeLastPrice") != null) {
			document.getElementById("tradeLastPrice").innerHTML = (data.last + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
		}
	};
	this.dealSpotBtcTicker = function (data) {
		// 更新title上的价格
		if(global.symbol == global.btc && document.title!=null && !isSpider() && data.last != 0) {
			var newTitle = this.refreshTitlePrice(data);
			if (newTitle != "") {
				document.title = global.btcSymbol + newTitle;
			}
		}
		
		if (!this.checkBanner()) {
			return;
		}
		if (data != null && data != '' && data != 'undefined') {
			if (document.getElementById("bannerAccountBtcLast") != null && data.last != null && data.last != '' && data.last != 'undefined') {
				document.getElementById("bannerAccountBtcLast").value = data.last;
				push.btclast = Number(document.getElementById('bannerAccountBtcLast').value);
			}
			if (document.getElementById("bannerBtcBuy") != null && data.buy != null && data.buy != '' && data.buy != 'undefined') {
				document.getElementById("bannerBtcBuy").value = data.buy;
			}
			if (document.getElementById("bannerBtcSell") != null && data.sell != null && data.sell != '' && data.sell != 'undefined') {
				document.getElementById("bannerBtcSell").value = data.sell;
			}
			AccountingUserAccountInfo();
			if (document.getElementById("canpush") != null) {
				_ChangeBalance();
			}
		}
		if (document.getElementById("bannerBtcLast") != null) {
			push.btclast = data.last;
			push.btcsell = data.sell;
			push.btcbuy = data.buy;
			document.getElementById("bannerBtcLast").innerHTML = (push.btclast + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
		}
		if (document.getElementById("bannerBtcVol") != null) {
			var tempBtc = data.vol + '';
			var end = tempBtc.indexOf('.');
			if (end == -1) {
				end = tempBtc.length;
			}
			document.getElementById("bannerBtcVol").innerHTML = tempBtc.substr(0, end);
		}
		//更新首页大图成交量
		if (document.getElementById("indexVol") != null) {
			document.getElementById("indexVol").innerHTML = data.vol;
		}
		if (global.symbol == 0 && document.getElementById("tradeLastPrice") != null) {
			document.getElementById("tradeLastPrice").innerHTML = (data.last + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
		}
	};
	
}

function depthManager() {
	this.buyDepthLength;
	this.sellDepthLength;
	this.isShow;
	this.dataInit = false;
	this.buyDepth;
	this.sellDepth;
	this.setDepthHtml = function (typeName, type, list, medianUnit) {
		var result = "";
		if (list == null) {
			return;
		}
		
		var oldNode = jQuery("#" + typeName);
		var listLength = list.length;
		var symbol = global.symbol;
		if (type == 0) {
			if (!this.buyDepthLength || this.buyDepthLength < 200 || listLength < 200) {
				for (var i = 0; i < listLength; i++) {
					var order = i + 1;
					result += "<li class='li-ct-transcation'  onclick='buyautoTrade(" + order + ")'>";
					result += "<div class='part-ct-transcation buy' style='width:55px;'>" + depth_buy + "(" + order + ")</div>";
					result += "<div class='part-ct-transcation_right'  style='padding: 0px 5px 0px 0px;width:70px;'>";
					result += "<span id='buyPriceSpan" + order + "'>" + CommaFormattedLittle(list[i][0], symbolSubPaltPoint(symbol)) + "</span>";
					result += "<input type='hidden' id='buyPrice" + order + "' value='" + list[i][0] + "' />";
					result += "</div>";
					result += "<div class='part-ct-transcation_right' style='padding-left: 0px'>";
					result += "<span id='buyAmountSpan" + order + "'>" + CommaFormattedLittle(list[i][1], symbolAmountSubPoint(symbol)) + "</span>";
					result += "<input type='hidden' id='buyAmount" + order + "' value='" + list[i][1] + "' />";
					result += "</div>";
					result += "<div class='part-ct-transcation'  style='padding-left:5px'>";
					result += "<span style='width:" + sortDepth.width(list[i][1], medianUnit) + "px;' class='buyspan' id='buySpanColor" + order + "'></span>";
					result += "</div>";
					result += "</li>";
				}
				this.buyDepthLength = listLength;
				oldNode.html(result);
			} else {
				for (var i = 0, order = 1; i < 200; i++, order++) {
					document.getElementById("buyPriceSpan" + order).innerHTML = CommaFormattedLittle(list[i][0], symbolSubPaltPoint(symbol));
					document.getElementById("buyPrice" + order).value = (list[i][0]);
					document.getElementById("buyAmountSpan" + order).innerHTML = CommaFormattedLittle(list[i][1], symbolAmountSubPoint(symbol));
					document.getElementById("buyAmount" + order).value = list[i][1];
					document.getElementById("buySpanColor" + order).style.width = sortDepth.width(list[i][1], medianUnit) + "px";
				}
			}
		} else {
			var j = 0;
			if (!setDepthHtml.sellDepthLength || setDepthHtml.sellDepthLength < 200 || listLength < 200) {
				for (var i = listLength - 1; i >= 0; i--) {
					var order = j + 1;
					result += "<li class='li-ct-transcation'  onclick='sellautoTrade(" + order + ")'>";
					result += "<div class='part-ct-transcation sell' style='width:55px;'>" + depth_sell + "(" + order + ")</div>";
					result += "<div class='part-ct-transcation_right'  style='padding: 0px 5px 0px 0px;width:70px;'>";
					result += "<span id='sellPriceSpan" + order + "'>" + CommaFormattedLittle(list[i][0], symbolSubPaltPoint(symbol)) + "</span>";
					result += "<input type='hidden' id='sellPrice" + order + "' value='" + list[i][0] + "' />";
					result += "</div>";
					result += "<div class='part-ct-transcation_right' style='padding-left: 0px'>";
					result += "<span id='sellAmountSpan" + order + "'>" + CommaFormattedLittle(list[i][1], symbolAmountSubPoint(symbol)) + "</span>";
					result += "<input type='hidden' id='sellAmount" + order + "' value='" + list[i][1] + "' />";
					result += "</div>";
					result += "<div class='part-ct-transcation'  style='padding-left:5px'>";
					result += "<span style='width:" + sortDepth.width(list[i][1], medianUnit) + "px;' class='sellspan' id='sellSpanColor" + order + "'></span>";
					result += "</div>";
					result += "</li>";
					j++;
				}
				setDepthHtml.sellDepthLength = listLength;
				oldNode.html(result);
			} else {
				for (var i = list.length - 1, order = 1; i >= 0; i--, order++) {
					document.getElementById("sellPriceSpan" + order).innerHTML = CommaFormattedLittle(list[i][0], symbolSubPaltPoint(symbol));
					document.getElementById("sellPrice" + order).value = list[i][0];
					document.getElementById("sellAmountSpan" + order).innerHTML = CommaFormattedLittle(list[i][1], symbolAmountSubPoint(symbol));
					document.getElementById("sellAmount" + order).value = list[i][1];
					document.getElementById("sellSpanColor" + order).style.width = sortDepth.width(list[i][1], medianUnit) + "px";
				}
			}
		}
	};
	this.dealIncrementDepth = function (data) {
		if (data.asks && data.asks.length > 0) {
			for (var i = this.sellDepth.length - 1; i >= 0; --i) {
				var itemPrice = +this.sellDepth[i][0];
				for (var j = 0; j < data.asks.length; ++j) {
					// [price amount]
					var sellArray = data.asks[j];
					var price = +sellArray[0];
					var amount = +sellArray[1];
					if (price == itemPrice) {
						if (amount == 0) {
							this.sellDepth.splice(i, 1);
						} else {
							this.sellDepth[i] = sellArray;
						}
						deal = true;
					} else if (price < itemPrice) {
						for (var k = 0; k < i; ++k) {
							this.sellDepth[k] = this.sellDepth[k+1];
						}
						this.sellDepth[i] = sellArray;
						deal = true;
					} else {
						if (this.sellDepth.length < 5) {
							for (var k = 0; k < this.sellDepth.length; ++k) {
								this.sellDepth[k + 1] = this.sellDepth[k];
							}
							this.sellDepth[0] = sellArray;
							deal = true;
						}
					}
					if (deal) {
						data.asks.splice(j, 1);
						j--;
					}
				}
			}
		} else if (data.bids && data.bids.length > 0) {
			for (var i = 0; i < this.buyDepth.length; ++i) {
				var itemPrice = +this.buyDepth[i][0];
				for (var j = 0; j < data.bids.length; ++j) {
					var buyArray = data.bids[j];
					var price = +buyArray[0];
					var amount = +buyArray[1];
					var deal = false;
					if (price == itemPrice) {
						if (amount == 0) {
							this.buyDepth.splice(i, 1);
						} else {
							this.buyDepth[i] = buyArray;
						}
						deal = true;
					} else if (price > itemPrice) {
						for (var k = this.buyDepth.length - 1; k >= i; --k) {
							this.buyDepth[k] = this.buyDepth[k-1];
						}
						this.buyDepth[i] = buyArray;
						deal = true;
					} else {
						if (this.buyDepth.length < 5) {
							this.buyDepth[this.buyDepth.length] = buyArray;
							deal = true;
						}
					}
					if (deal) {
						data.bids.splice(j, 1);
						j--;
					}
				}
			}
		}
		this.renderingDepth();
	};
	this.initData = function (data) {
		var bids = data.bids;
		var asks = data.asks;
		this.sort(bids);
		this.sort(asks);
		
		this.buyDepth = bids.slice(0, 5);
		var sellStart = 0;
		if (asks.length >= 5) {
			sellStart = asks.length - 5;
		}
		this.sellDepth = asks.slice(sellStart, asks.length);
		this.buyDepthLength = this.buyDepth.length;
		this.sellDepthLength = this.sellDepth.length;
	};
	this.sort = function(data) {
		for (var i = 0; i < data.length; ++i) {
			for (var j = i+1; j < data.length; ++j) {
				if (+data[i][0] < +data[j][0]) {
					var tmp = data[i];
					data[i] = data[j];
					data[j] = tmp;
				}
			}
		}
	};
	this.depth5 = function (data) {
		this.initData(data);
		this.renderingDepth();
		this.dataInit = true;
	};
	this.renderingDepth = function () {
		var symbol = global.symbol;
		var buyDepthList = this.buyDepth;
		var sellDepthList = this.sellDepth;
		
		if (sellDepthList != null) {
			var j = 0;
			var i = sellDepthList.length - 1;
			for (var k = 0; k < 5; k++, j++, i--) {
				var y = j + 1;
				if (j >= 5) {
					break;
				}
				var sellPriceSpan = document.getElementById("sellPriceSpan" + y);
				if (!sellPriceSpan&&!!sellDepthList[i]) {
					var result = getDepthHtml("sell", y, sellDepthList[i], symbol);
					jQuery("#sellList").prepend(result);
					continue;
				}
				if (!sellDepthList[i]) {
					jQuery(sellPriceSpan).parent().hide();
					continue;
				}
				jQuery(sellPriceSpan).parent().show();
				sellPriceSpan.innerHTML = CommaFormattedByOriginal(CommaFormattedCommon(sellDepthList[i][0], symbolSubPoint(symbol)));
				document.getElementById("sellAmountSpan" + y).innerHTML = CommaFormattedByOriginal(CommaFormattedCommon(sellDepthList[i][1], symbolAmountSubPoint(symbol)));
				document.getElementById("sellPrice" + y).value = sellDepthList[i][0];
				document.getElementById("sellAmount" + y).value = sellDepthList[i][1];
			}
			
		}
		if (buyDepthList != null) {
			for (var i = 0; i < 5; i++) {
				var y = i + 1;
				if (y > 5) {
					break;
				}
				var buyPriceSpan = document.getElementById("buyPriceSpan" + y);
				if (!buyPriceSpan&&!!buyDepthList[i]) {
					var result = getDepthHtml("buy", y, buyDepthList[i], symbol);
					jQuery("#buyList").append(result);
					continue;
				}
				if (!buyDepthList[i]) {
					jQuery(buyPriceSpan).parent().hide();
					continue;
				}
				jQuery(buyPriceSpan).parent().show();
				buyPriceSpan.innerHTML = CommaFormattedByOriginal(CommaFormattedCommon(buyDepthList[i][0], symbolSubPoint(symbol)));
				document.getElementById("buyAmountSpan" + y).innerHTML = CommaFormattedByOriginal(CommaFormattedCommon(buyDepthList[i][1], symbolAmountSubPoint(symbol)));
				document.getElementById("buyPrice" + y).value = buyDepthList[i][0];
				document.getElementById("buyAmount" + y).value = buyDepthList[i][1];
			}
		}
	};
	
	this.changeDepthImg_com = function () {
		var dept = new CookieClass();
		var deptMerge = dept.getCookie("deptMerge_stock");
		if (deptMerge == 0) {
			jQuery("#deptMerge_stock_btn IMG:eq(0)").css("display", "");
			jQuery("#deptMerge_stock_btn IMG:eq(1)").css("display", "none");
		} else {
			jQuery("#deptMerge_stock_btn IMG:eq(0)").css("display", "none");
			jQuery("#deptMerge_stock_btn IMG:eq(1)").css("display", "");
		}
	};
	
	this.handleDepthData = function (data) {
		this.depth5(data);
	};
	
	this.changeMergeType = function () {
		this.dataInit = false;
		var newMergeType;
		
		// 三选一
		var symbol = global.symbol;
		var oldMergeType = +getCookieValue("deptMerge_stock");
		if (symbol == 0 && global.siteFlag == 1) {
			jQuery("#deptMerge_burst_btn a").each(function (i, val) {
				if (jQuery(val).hasClass('cur')) {
					newMergeType = jQuery(val).attr('code');
				}
			});
		} else {
			if (oldMergeType == "undefined" || oldMergeType == 0 || !oldMergeType) {
				newMergeType = 1;
				this.clean();//清除缓存
			} else if (oldMergeType == 1 || oldMergeType == 2) {
				newMergeType = 0;
			}
		}
		
		if (oldMergeType == newMergeType) {
			return;
		}
		setCookieValue("deptMerge_stock", newMergeType);
		if (symbol == 1 || global.siteFlag == 2) {
			changeDepthImg_com();
			jQuery("#depthMergeStock").val(newMergeType);
		}
		
		if (webSocket.isConnection()) {
			
			global.merge = newMergeType;
			var newDepthType = WsUtils.getSubSpot5Depth(global.symbol, newMergeType, global.siteFlag);
			var oldDepthType = WsUtils.getSubSpot5Depth(global.symbol, oldMergeType, global.siteFlag);
			webSocket.addSub(newDepthType, dealSpotDepth);
			webSocket.rmSub(oldDepthType);
		}
		this.mergeType = newMergeType;
	};
	this.getBuyDepthList = function (depthList) {
		if (!this.buyDepth) {//第一次加载为空的时候
			this.buyDepth = depthList;
			return depthList;
		}
		if (!!depthList) {
			for (var i = 0; i < depthList.length; i++) {
				var price = depthList[i][0];
				var amount = depthList[i][1];
				var index = this.buyDepth.binarySearchDesc(price);
				if (Number(amount) == 0) {//删除
					this.buyDepth.splice(index, 1);
					continue;
				}
				if (index != -1) {//修改
					this.buyDepth[index] = depthList[i];
					continue;
				}
				if (index == -1) {//增加
					this.buyDepth.push(depthList[i]);
					continue;
				}
			}
			//重新排序
			this.buyDepth.sort(function (o1, o2) {
				return Number(o2[0]) - Number(o1[0]);
			});
			//删除超过200的
			if (this.buyDepth.length > 200) {
				this.buyDepth.splice(200, this.buyDepth.length - 200);
			}
		}
		return this.buyDepth;
	};
	this.getSellDepthList = function (depthList) {
		if (!this.sellDepth) {//第一次加载为空的时候
			this.sellDepth = depthList;
			return depthList;
		}
		if (!!depthList) {
			for (var i = 0; i < depthList.length; i++) {
				var price = depthList[i][0];
				var amount = depthList[i][1];
				var index = this.sellDepth.binarySearchDesc(price);
				if (Number(amount) == 0) {//删除
					var tmp = this.sellDepth.splice(index, 1);
					continue;
				}
				if (index != -1) {//修改
					this.sellDepth[index] = depthList[i];
					continue;
				}
				if (index == -1) {//增加
					this.sellDepth.push(depthList[i]);
					//console.info("增加-------"+price+"---amount"+amount);
					continue;
				}
			}
			//重新排序
			this.sellDepth.sort(function (o1, o2) {
				return Number(o2[0]) - Number(o1[0]);
			});
			//删除超过200的
			if (this.sellDepth.length > 200) {
				this.sellDepth.splice(0, this.sellDepth.length - 200);
			}
		}
		return this.sellDepth;
	};
	this.clean = function () {
		this.buyDepth = null;
		this.sellDepth = null;
	};
}

